package com.sunkyc.controller.system;


import cn.dev33.satoken.annotation.SaCheckPermission;
import com.sunkyc.commons.annotation.ReqLog;
import com.sunkyc.commons.entity.R;
import com.sunkyc.commons.exception.CustomerException;
import com.sunkyc.framework.system.entity.SysUser;
import com.sunkyc.framework.system.service.SysUserService;
import com.sunkyc.commons.entity.PageQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.sunkyc.commons.entity.TablePageData;
/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author sunkyc
 * @since 2022-05-31
 */
@RestController
@RequestMapping("/sysUser")
@Api(tags = "用户信息管理")
@RequiredArgsConstructor
public class SysUserController {
    private final SysUserService baseService;

    @GetMapping("/list")
    @ApiOperation("用户分页")
    @SaCheckPermission("system-user-list")
    public R<TablePageData<SysUser>> queryList(PageQueryVo pageQueryVo, SysUser sysUser){
        return R.ok(baseService.queryList(pageQueryVo,sysUser));
    }


    @GetMapping("/{userId}")
    @ApiOperation("用户查询[id]")
    @SaCheckPermission("system-user-query")
    @ReqLog
    public R<SysUser> queryById(@PathVariable("userId") Long userId){
        return R.ok(baseService.queryById(userId));
    }


    @PostMapping
    @ApiOperation("用户添加")
    @SaCheckPermission("system-user-add")
    @ReqLog
    public R<Void> addUser(@RequestBody @Validated SysUser user){
        checkedFiled(user);
        return R.result(baseService.addUser(user));
    }

    @PutMapping
    @ApiOperation("用户修改")
    @SaCheckPermission("system-user-update")
    @ReqLog
    public R<Void> updateUser(@RequestBody @Validated SysUser user){
        checkedFiled(user);
        return R.result(baseService.updateUser(user));
    }

    @PutMapping("/resetPwd")
    @ApiOperation("重置密码")
    @SaCheckPermission("system-user-respwd")
    @ReqLog
    public R<Void> restPwd(@RequestBody @Validated SysUser user){
        return R.result(baseService.restPwd(user));
    }

    @DeleteMapping("/{ids}")
    @ApiOperation("用户删除[批量]")
    @SaCheckPermission("system-user-delete")
    @ReqLog
    public R<Void> delUser(@PathVariable("ids") Long[] ids){
        return R.result(baseService.delUser(ids));
    }


    /**
     * 校验用户字段信息
     */
    private void checkedFiled(SysUser user){
        if(baseService.checkedUserNameUnique(user)){
            throw new CustomerException("添加失败：用户名 ["+user.getUserName()+"] 已被使用");
        }
        if(baseService.checkedPhoneUnique(user)){
            throw new CustomerException("添加失败：电话号码 ["+user.getPhonenumber()+"] 已被使用");
        }
        if(baseService.checkedEmailUnique(user)){
            throw new CustomerException("添加失败：邮箱 ["+user.getEmail()+"] 已被使用");
        }
    }

}
